package com.wwj.aicodemother.aop;

import com.wwj.aicodemother.annotation.AuthCheck;
import com.wwj.aicodemother.exception.BusinessException;
import com.wwj.aicodemother.exception.ErrorCode;
import com.wwj.aicodemother.model.entity.User;
import com.wwj.aicodemother.model.enums.UserRoleEnum;
import com.wwj.aicodemother.service.UserService;
import jakarta.annotation.Resource;
import jakarta.servlet.http.HttpServletRequest;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestAttributes;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

@Aspect
@Component
public class AuthInterceptor {

    @Resource
    private UserService userService;

    /**
     * 拦截带有AuthCheck注解的方法
     * @param joinPoint
     * @param authCheck 权限注解校验
     * @return
     * @throws Throwable
     */
    @Around("@annotation(authCheck)")
    public  Object doIntecept(ProceedingJoinPoint joinPoint, AuthCheck authCheck) throws Throwable {
        String mustRole = authCheck.mustRole();
        RequestAttributes requestAttributes = RequestContextHolder.currentRequestAttributes();
        HttpServletRequest request = ((ServletRequestAttributes) requestAttributes).getRequest();
        //获取当前登录用户
        User loginUser = userService.getLoginUser(request);
        UserRoleEnum mustRoleEnum = UserRoleEnum.getEnumByValue(mustRole);
        //不需要权限直接放行
        if (mustRoleEnum == null) {
            return joinPoint.proceed();
        }
        //校验用户角色
        UserRoleEnum enumByValue = UserRoleEnum.getEnumByValue(loginUser.getUserRole());
        //无权限，直接拒绝
        if (enumByValue == null) {
            throw new BusinessException(ErrorCode.NO_AUTH_ERROR, "无权限");
        }
        //要求有管理员权限，但当前用户没有
        if (UserRoleEnum.ADMIN.equals(mustRoleEnum) && !UserRoleEnum.ADMIN.equals(enumByValue)) {
            throw new BusinessException(ErrorCode.NO_AUTH_ERROR, "无权限");
        }
        //有权限，放行
        if (enumByValue.equals(mustRoleEnum)) {
            return joinPoint.proceed();
        }
        return joinPoint.proceed();
    }
}
